package model.item;
import java.util.ArrayList;
import java.util.List;

import model.Model;
import utilities.*;

public class Inventory extends Model implements Archiveable {
	
	private List<TakeableItem> items; 
	
	public Inventory()
	{
		super("Item Inventory");
		items = new ArrayList<TakeableItem>(10);
	}
	
	public Inventory(List<TakeableItem> list)
	{
		super("Item Inventory");
		items = list; 
	}
	
	public void addItem(TakeableItem item)
	{
		items.add(item);
		super.updateSubscribers();
	}
	
	public TakeableItem removeItem(TakeableItem item)
	{
		TakeableItem returnedItem = null;
		if(!items.contains(item))
			return returnedItem;
		else
		{
			int index = items.indexOf(item);
			returnedItem = items.remove(index);
			super.updateSubscribers();
			return returnedItem;
		}
	}

	public boolean contains(TakeableItem item)
	{
		return items.contains(item);
	}
	
	public List<TakeableItem> getItems()
	{
		return items;
	}
	
	public Archive save() {
		Archive archive = super.save();
		
		List<String> itemClassList = new ArrayList<String>();
		for (TakeableItem item : this.items) {
			itemClassList.add(item.getClass().getName());
		}
		archive.putAttributeList("itemClassList", itemClassList);
		archive.putManyRelationship("items", this.items);
		
		return archive;
	}
	
	public void load(Archive archive) {
		super.load(archive);
		
		List<String> itemClassList = archive.getAttributeList("itemClassList");
		List<Archive> itemArchives = archive.getManyRelationship("items");
		this.items = new ArrayList<TakeableItem>();
		for (int i = 0; i < itemClassList.size(); i++) {
			TakeableItem item = (TakeableItem)ModelFactory.getInstance().createInstanceWithClassName(itemClassList.get(i));
			item.load(itemArchives.get(i));
			this.items.add(item);
		}
	}
	
}
